#include "udpsocket.h"

udpsocket::udpsocket(QObject *parent)
{
    Q_UNUSED(parent);
    connect(this, SIGNAL(readyRead()),
            this, SLOT(processPendingDatagrams()));
}

bool udpsocket::socketBind(quint16 port)
{
    return bind(port, QUdpSocket::ShareAddress);
}

qint64 udpsocket::socketWrite(const QByteArray &datagram, quint16 port)
{
    return writeDatagram(datagram, QHostAddress::Broadcast, port);
}

bool udpsocket::hasPending()
{
    return hasPendingDatagrams();
}

QString udpsocket::socketRead()
{
    QByteArray datagram;

    datagram.resize(pendingDatagramSize());
    readDatagram(datagram.data(), datagram.size());

    return QString(datagram);
}

void udpsocket::processPendingDatagrams()
{
    while (hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(pendingDatagramSize());
//        qDebug () << datagram;
        readDatagram(datagram.data(), datagram.size());
        // messageReceive(QString(datagram));
        dealReceiveData(datagram);
    }
}

void udpsocket::dealReceiveData(const QByteArray &ba)
{
    //qDebug() << ba;
    QByteArray start;
    start.append(0xaa);
    //start.append(0x55);

    QByteArray end;
    end.append(0xcc);
    end.append(0x33);
    end.append(0xc3);
    end.append(0x3c);

    receiveData.append(ba);
    int startPos = receiveData.indexOf(start);
    int endPos = receiveData.indexOf(end);
    QByteArray cmd;
    if (startPos >= 0 && endPos >=0) {
        int len = endPos - startPos + end.length();
        cmd = receiveData.mid(startPos + start.size(), len - end.size() - start.size());
        emit messageReceive(cmd.toHex());
        //emit messageReceiveInt(QString(cmd.at(0)).toInt());

        //qDebug() << cmd.left(1).toHex();
        //qDebug() << cmd.toHex() << cmd.size() << cmd.toHex().size();
        receiveData.remove(startPos, len);

        //qDebug() << receiveData.length();
    }

//    if (!cmd.isEmpty()) {
//        switch (cmd.at(1)) {
//        case 1:
//            ui->progressBar->setValue(ui->progressBar->maximum() / 4 * cmd.at(2));
//            break;
//        case 2:
//            if (cmd.at(2))
//                ui->label_zaw->setText("正常");
//            else
//                ui->label_zaw->setText("警告");
//            update();
//            break;
//        case 3:
//            if (cmd.at(2))
//                ui->label_daohang->setText("正常");
//            else
//                ui->label_daohang->setText("警告");
//            update();
//            break;
//        case 4:
//            if (cmd.at(2))
//                ui->label_qudong->setText("正常");
//            else
//                ui->label_qudong->setText("警告");
//            update();
//            break;
//        case 5:
//            if (cmd.at(2))
//                ui->label_zaw->setText("正常");
//            else
//                ui->label_zaw->setText("警告");
//            update();
//            break;
//        default:
//            break;
//        }
//    }
}
